// mine/address/address.js
const request = require('../../util/request')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        addressList:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getAddress()
    },

    //修改信息
    change(e){
        let index = e.currentTarget.dataset.index
        let address = this.data.addressList[index]._id
        wx.navigateTo({
          url: '../addAddress/addAddress?address='+address,
        })
    },

    //删除当前项
    delete(e){
        let index = e.currentTarget.dataset.index
        let address = this.data.addressList[index]._id
        wx.showModal({
            title: '提示',
            content: '是否删除收货地址',
            success:res =>{
              if (res.confirm) {
                request.delete('/wx/address/delete',{address}).then(res =>{
                    this.getAddress()
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 2000
                    })
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
    },

    //改变默认选中状态
    changeDefault(e){
        let index = e.currentTarget.dataset.index
        let address = this.data.addressList[index]._id
        let memberId = this.data.addressList[index].memberId
        let isDefault = !this.data.addressList[index].isDefault
        request.put('http://localhost:3000/wx/address/default',{address,memberId,isDefault}).then(res =>{
            this.getAddress()
        })
    },

    addAddress(){
        wx.navigateTo({
          url: '../addAddress/addAddress',
        })
    },
    
    //获取地址信息
    getAddress(){
        request.get('http://localhost:3000/wx/address').then(res =>{
            if(res.errorMsg){
                console.log(res.errorMsg)
            }else{
                this.setData({
                    addressList:res
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getAddress()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})